/**
 * Created by way on 16/9/17.
 */
const $ = require('../lib/kdom');
import cfg from '../config';
import DEVICE from '../lib/kdevice';
import Ws from '../lib/kws';
import * as ajax from '../lib/kajax';
import { setTitle, urlParam, session, getHash, format, jsons, json } from '../lib/kutil';
import { tabSwitch } from '../util/aid';
import { get, post, getView, token } from '../util/api';

import Dialog from '../lib/kdialog';
const dialog = new Dialog();
// import {dateStr} from '../util/tool';

let _view = require('raw-loader!./join.html'); // eslint-disable-line
// let _view = '';
let closeDate = {};
let txFrom = null;
let txTo = null;
//建立ws 连接
$._ws = null;
let user = null;
let issueId = null;
let oneIssue = null;
let onlinePid = null;
let userInfos = null;
let sid = 11;
let tab = 1;
let perm = "";
let servicePid = [];
let allUsersInfos = null;
// let pid = 11;
let site = null; // site 参数
// test
let companyData =
  {
    "name": "诺亚大陆有限公司",
    "logo": "http://www.nuoyadalu.com/img/nydlqr.jpg",
    "url": "http://www.nuoyadalu.com/",
    "address": "重庆市渝北区黄山大道中55号麒麟C座1203",
    "email": "walteryu@163.com",
    "explian": "14岁小女孩异想天开，参加2015年科技部“中国创新创业大赛”，广东省互联网行业团队第一，国家奖励100万，2016年5月22日深圳卫视“合伙中国人”融资节目，成功获得当当网李国庆、58同城姚劲波投资承诺"
  };

export default class {
  path = '/ogs/join$';
  hash = '/ogs/join';
  title = '在线服务';

  constructor(opt) {
    opt = opt || {};
    this.path = opt.path || this.path;
    this.hash = opt.hash || this.hash;
    this.title = opt.title || this.title;
  }

  // 输出视图
  view(cb) {
    if (!_view) {
      // 静态资源浏览器有缓存,增加时标,强制刷新!
      getView(`${cfg.ogs.view.host}${cfg.ogs.view.join}?t=${(+new Date())}`, '', (rs) => {
        _view = rs;
        cb(null, _view);
      });
    } else
      cb(null, _view);
  }

  // 在已经加载的视图上操作
  bind(dv, params) {
    console.log('聊天页面', params);
    dialog.loading();
    site = localStorage.getItem(cfg.app.nauoyaSite);
    site = site ? JSON.parse(site) : '';
    // sid = urlParam('pid') || urlParams('pid');
    // issueId = urlParam('issueId') || urlParams('issueId');
    // bindLink(btnSend, ()=>{
    //   sendMsg();
    // });

    // 1用户进入方式 2客服进入方式 3专家客服和线下客服进入方式一样都是已推送消息的形式进入。
    //进来就获取所有用户信息。。方便拿到头像昵称等各种展示界面的信息。如果有单独获取一个用户的信息就更好了。
    getAllUsers(cb => {
      //全局保存所用用户信息
      allUsersInfos = cb;
      // console.log("所有人信息", cb);

      if (params.userInfo) {
        userInfos = params.userInfo;
        // console.log("页面传值过来的用户信息:", userInfos)
        perm = userInfos.perm[0];

        if (params.issueId) {
          issueId = userInfos.issueId;
        }
        if (params.issueInfo) {
          oneIssue = params.issueInfo;
          issueId = oneIssue.id;
          if (oneIssue.serviceId.length > 0) {
            servicePid[0] = oneIssue.serviceId[0];
          }
        }
        if (params.opts) {
          sid = params.opts.sid;
          tab = params.opts.tab;
        }
        txFrom = userInfos.pid;
        if (txFrom) {
          $._ws = new Ws({ url: `${cfg.ogs.ws}`, pid: txFrom, time: 5 });
          $._ws.onopen = (s) => {
            console.log(s)
          };
          $._ws.onmsg = (s) => {
            console.log("有消息来咯:", s);

            if (s.indexOf('"H":200') > -1
              || s.indexOf('"M":200') > -1
              || s.indexOf('"M.G":200') > -1)
              return;

            // alert(s);

            if (s.indexOf('{') > -1) {
              s = s ? JSON.parse(s) : {};
              if (s.M || s['M.G']) {
                s.M = s.M || s['M.G']; // 兼容群发的消息
                // 屏蔽消息
                leftMsg(s);
              }
            }
          };
        }
        // console.log("自己的PID[txFrom]", txFrom);
        // ifIosFooter();
        if (perm) {
          switch (perm) {
            case 10:
              //用户
              onlinePid = site.service[0][0];
              checkIsHadIssue(rs => {
                console.log('加载工单', rs);
                if (rs) {
                  //加载工单
                  if (oneIssue.serviceId[0]) {
                    txTo = oneIssue.serviceId[0];
                  }
                  getMsgList(issueId, userInfos);
                } else {
                  // txTo = txFrom;
                  createHtml(userInfos);
                }
              })
              createHtml(userInfos)
              break;
            case 11:
              //专家
              createHtml(userInfos)
              break;
            case 12:
              console.log("专家的issue" + issueId);
              txTo = oneIssue.serviceId[0];
              getMsgList(issueId, userInfos);
              break;
            case 13:
              //网点线下服务
              txTo = oneIssue.serviceId[0];
              getMsgList(issueId, userInfos);
              break;
            default:
              getMsgList(issueId, userInfos);
              break;
          }
        }
      }
      //根据perm判断权限
      // autoTextarea($.id("txSend"));
    })
  }
}

//左边的信息
function leftMsg(s) {
  console.log("接受到的消息:", s);
  let msg = toObject(s);
  //需要获取头像
  if (perm != 10) {
    //非用户都是群发群收消息
    if (msg.TP == issueId) {
      showMsgLeft(s);
    }
  } else {
    //用户只能接受客服的消息 第一次txTo是的群号.
    if (msg.FW == 1 && msg.TP == issueId) {
      showMsgLeft(s);
    }
  }
}

//客户进入页面查询工单 如果有工单返回issueId 如果没有返回空
function checkIsHadIssue(cb) {
  ajax.get(`${cfg.ogs.host}${cfg.ogs.getOrder}`, "", (rs) => {
    // console.log('客户进入页面查询工单 ', rs);
    if (rs) {
      // alert("用户自己的pid"+txFrom);
      let r = JSON.parse(rs);
      for (let i = 0, len = r.length; i < len; i++) {
        if (r[i].pid == userInfos.pid && r[i].status != 2) {
          issueId = r[i].id;
          oneIssue = r[i];
          break;
        }
      }
      cb(issueId, oneIssue);
    } else {
      alert('获取工单失败');
    }
  });
}

// 检查工单
function getOneIssueStatus(issueId, cb) {
  // {"rc":200,"data":{"_id":"59853b03a45e5e5d3c84f284","status":0,"rating":[]}}
  get(`${cfg.ogs.host}${cfg.ogs.checkIssue}`, 'id=' + issueId, (rs) => {
    console.log('evaluate checkIssue:   ', rs);
    if (rs) {
      let r = JSON.parse(rs);
      if (r.rc == 200) {
        cb(r.data.status);
      }
    }
    // dialog.close();
  });
}

//获取一个工单
function getOneIssue(issueNo, cb) {
  ajax.get(`${cfg.ogs.host}${cfg.ogs.getOrder}`, "", (rs) => {
    if (rs) {
      // alert(rs);
      let r = JSON.parse(rs);
      for (let i = 0, len = r.length; i < len; i++) {
        if (r[i].id == issueNo) {
          cb(r[i]);
          break;
        }
      }
    } else {
      alert('您好！获取消息列表失败！');
    }
  });
}

// 获取一个工单的信息列表
function getMsgList(data, user) {
  let arr = [];
  let infoBox = $.qu(".aui-chat");
  infoBox.innerHTML = "";
  ajax.get(`${cfg.ogs.host}${cfg.ogs.msgList}`, `issueId=${data}`, (rs) => {
    if (rs) {
      rs = JSON.parse(rs);
      console.log("一个工单所有信息:", rs)
      for (let i = 0, len = rs.data.length; i < len; i++) {
        let rsd = toObject(rs.data[i]);
        if (rsd.msg.M || rsd.msg["M.G"]) {
          //兼容群发单发消息
          rsd.msg.M = rsd.msg.M || rsd.msg["M.G"];
          if (rsd.from != user.pid) {
            addChatLeft(rsd)
          } else {
            addChatRight(rsd)
          }
        }
      }
      createHtml(userInfos);
    }
  });
}

//加载工单信息右边的消息
function addChatRight(data) {
  const msgBox = $.qu(".aui-chat");
  let rs = toObject(data);
  const dv = document.createElement('div');
  dv.className = 'aui-chat-item aui-chat-right';
  dv.innerHTML = `<div class="aui-chat-media">
              <img src="${rs.member[1]}">
          </div>
          <div class="aui-chat-inner">   
              <div class="aui-chat-content">
                  <div class="aui-chat-arrow"></div>
                  ${rs.msg.M}
              </div>
              <div class="aui-chat-status">
                  <i class="aui-iconfont aui-icon-info aui-text-danger"></i>
              </div>
          </div>`;
  msgBox.appendChild(dv);
  msgBox.scrollTop = msgBox.scrollHeight;
}

//加载工单信息左边的消息
function addChatLeft(data) {
  let rs = toObject(data);
  if (rs.msg) {
    if (perm != 10) {
      //非用户加载任何信息
      permAddLeftMsg(rs);
    } else {
      //用户只加载与自己有关的信息
      if (rs.msg.T == userInfos.pid) {
        permAddLeftMsg(rs)
      }
    }
  }
}

function permAddLeftMsg(data) {
  let rs = toObject(data);
  const msgBox = $.qu(".aui-chat");
  const dv = document.createElement('div');
  dv.className = 'aui-chat-item aui-chat-left';
  dv.innerHTML = `<div class="aui-chat-media">
            <img src="${rs.member[1]}">
          </div>
          <div class="aui-chat-inner">
            <div class="aui-chat-content">
              <div class="aui-chat-arrow"></div>
              ${rs.msg.M}
            </div>
            <div class="aui-chat-status">
                <i class="aui-iconfont aui-icon-info aui-text-danger"></i>
            </div>
          </div>`;
  msgBox.appendChild(dv);
  msgBox.scrollTop = msgBox.scrollHeight;
}

function saveMsg(fw) {
  //perm = ""(用户):用户创建
  let tm = parseInt(new Date().getTime() - Date.parse('2000/01/01'));
  let mymsg = format('{"M":"%s", "F":"%s", "T":"%s", "FW":"%s", "TM":%d, "TP":"%s", "SQ":%d, "ST":%d}',
    txSend.value, txFrom, txTo, fw, tm, issueId, 123, 1);
  // alert(`mymsg ${JSON.stringify(mymsg)}`)
  let orderData = {
    issueId: issueId,
    from: txFrom,
    to: txTo,
    msg: mymsg,
    pic: [],
    member: JSON.stringify([userInfos.name, userInfos.headimgurl]),
    status: 1
  };
  ajax.post(cfg.ogs.host + cfg.ogs.saveMsg, orderData, (err, rs) => {
    if (rs) {
      rs = JSON.parse(rs);
      if (rs.rc == 200) {
        //群发消息
        // alert(mymsgs);
        console.log("保存消息成功", rs);
        //$.id("sendMsgBtn").style.background = "#999";
      } else {
        // alert("保存信息失败");
      }
    } else {
      // alert("保存信息失败");
    }
  });
}

function bindLink(link, cb) {
  let touchStartY;
  link.ontouchstart = (e) => {
    touchStartY = e.changedTouches[0].clientY;
  };
  link.ontouchend = (e) => {
    e.preventDefault();
    if (Math.abs(e.changedTouches[0].clientY - touchStartY) > 10)
      return;
    cb();;
  };
}

function sendMsg() {
  //第一次发送消息创建工单
  if ($.qus(".aui-chat-item").length === 0) {
    createOrder(4);
  } else {
    // 判断是否有专职接单
    if (servicePid.length == 0) {
      getOneIssue(issueId, cb => {
        console.log('用户发送信息的回调函数的返回值', cb);
        if (cb.serviceId.length > 0) {
          //发给专职
          servicePid.push(cb.serviceId[0]);
          txTo = cb.serviceId[0];
        } else {
          // 群发;
          txTo = onlinePid;
        }
        sendAllMsg(4);
      })
    } else {
      txTo = servicePid[0];
      sendAllMsg(4);
    }
  }
}

// 根据权限绑定点击事件
function bindPermClick(userInfos) {
  switch (perm) {
    case 10:
      //用户发消息给专职客服群发。
      bindLink(btnSend, () => {
        sendMsg();
      });
      break;

    case 12:
      exportSend();
      break;
    case 13:
      bindLink(btnSend, () => {
        sendAllMsg(1)
      });
      break;
    default:
      //领导只查看信息
      break;
  }
}

// 创建工单 只有用户可以创建  1用户 2专家 3线下  4专职
function createOrder(fw) {
  let data = {
    "title": userInfos.name//咨询人 昵称-公司
    , "text": txSend.value //咨询内容
    , "pic": [] //消息图片
    , "member": JSON.stringify([userInfos.headimgurl, userInfos.name]) // 用户组 {name:'heping',img:'头像',pid:''}
    , "group": []
    , pid: userInfos.pid
  };
  ajax.post(`${cfg.ogs.host}${cfg.ogs.createOrder}`, data, (err, rs) => {
    if (rs) {
      console.log("创建工单返回值:", rs);
      rs = JSON.parse(rs);
      if (rs.rc == 200) {
        issueId = rs.data.id;
        //创建工单成功过后才让发送消息并展示到页面
        $._ws.msg(txTo, txSend.value, fw, issueId, 123, 1);
        //show msg
        rightMsg(txSend.value);
        //clear msg
        txSend.value = "";
        // alert("创建工单成功!");
      } else {
        alert("保存工单失败");
      }
    } else {
      alert("保存工单失败");
    }
  });
}

// 根据权限展示页面
function createHtml(userInfos) {
  // let perm = JSON.parse(userInfos);
  let str1 = "";
  let str = "";
  if (perm) {
    switch (perm) {
      case 10:
        bindPermClick(userInfos);
        dialog.close();
        break;
      case 11:
        $.id("footerBox").style.display = "none";
        $.id("chatListBox").innerHTML = `<h3 style="font-size:1.2rem;color:#666;text-align:center;margin-top:4rem;padding:.7rem;">专职客服请查看pc端</h3>`;
        dialog.close();
        break;
      case 12:
        hideFooter();
        dialog.close()
        createAlertHtml();
        break;
      case 13:
        hideFooter()
        dialog.close();
        bindPermClick(userInfos);
        break;
      default:
        $.id("footerBox").style.display = "none";
        dialog.close();
        break;
    }
  }
}
//关闭的工单不能再发消息
function hideFooter() {
  if (oneIssue.status == 2) {
    $.id("footerBox").style.display = "none";
  }
}

function createAlertHtml() {
  let obj = $.id("alertBox");
  let str = "";
  str += `<div class="chooseBox">
            <h3>请选择发送的人!<img src="http://cas-10038118.cossh.myqcloud.com/ogs/img/closeBtn.svg" id="closeAlertBtn"></img></h3>
            <div class="persImg">
                <div class="item-box" id="reUser">
                    <img src="http://cas-10038118.cossh.myqcloud.com/ogs/img/user.svg" alt="">
                    <p>请转发用户</p>
                </div>
                <div class="item-box" id="reService" style="display:none;">
                    <img src="http://cas-10038118.cossh.myqcloud.com/ogs/img/service.svg" alt="">
                    <p>转在线客服</p>
                </div>
                <div class="item-box" id="reManager">
                    <img src="http://cas-10038118.cossh.myqcloud.com/ogs/img/netservice.svg" alt="">
                    <p>请转线下网点</p>
                </div>
            </div>
        </div>`;
  obj.innerHTML = str;
  bindPermClick(userInfos);
}

function exportSend() {
  bindLink(btnSend, () => {
    if (!txSend.value) return;
    showAlert();
  });
  bindLink(closeAlertBtn, () => {
    closeAlert()
  });
  bindLink(reUser, () => {
    sendAllMsg(1);
    closeAlert()
  });
  bindLink(reService, () => {
    sendAllMsg(4);
    closeAlert()
  });
  bindLink(reManager, () => {
    sendAllMsg(3);
    closeAlert()
  });
}

function closeAlert() {
  $.id("alertBox").style.display = "none";
}
function showAlert() {
  $.id("alertBox").style.display = "flex";
}

function sendAllMsg(fw) {
  if (!txSend.value) return;
  getOneIssueStatus(issueId, cb => {
    if (cb == 2) {
      alert("当前工单已经关闭");
      footerBox.style.display = "none";
    } else {
      if (perm != 10) {
        $._ws.msg(txTo, txSend.value, fw, issueId, 123, 1);
        // if(servicePid.length == 0){
        //   // alert("群发消息"+onlinePid);
        //   $._ws.group(txTo, txSend.value, fw, issueId, 123, 1);    
        // }else{
        //   // alert("单发消息"+txTo);
        //   $._ws.msg(txTo, txSend.value, fw, issueId, 123, 1);      
        // }
      } else {
        $._ws.msg(txTo, txSend.value, fw, issueId, 123, 1);
      }
      rightMsg(txSend.value);
      //保存消息
      saveMsg(fw);
      txSend.value = "";
    }
  })
}

function showMsgLeft(msgs) {
  let userimg = getName(allUsersInfos, msgs.F);
  let ms = typeof msgs == "object" ? msgs : JSON.parse(msgs);
  // alert(ms.M);
  const msgBox = $.qu(".aui-chat");
  const dv = document.createElement('div');
  dv.className = 'aui-chat-item aui-chat-left';
  let str = "";
  str += `<div class="aui-chat-media">
                <img src='${userimg[0]}'>
            </div>
            <div class="aui-chat-inner">
            <div class="aui-chat-content">
                <div class="aui-chat-arrow"></div>${ms.M}</div>
            <div class="aui-chat-status">
              <i class="aui-iconfont aui-icon-info aui-text-danger"></i></div></div>`;
  dv.innerHTML = str;
  msgBox.appendChild(dv);
  msgBox.scrollTop = msgBox.scrollHeight;
}

function getName(data, id) {
  //昵称和头像 以数组的形式返回
  // console.log(data);
  let arr = [];
  let img = null;
  let name = null;
  if (data) {
    for (let i = 0, len = data.length; i < len; i++) {
      if (data[i].pid == id) {
        name = data[i].name;
        if (data[i].hasOwnProperty("headimgurl")) {
          img = data[i].headimgurl;
        } else {
          img = "http://cas-10038118.cossh.myqcloud.com/ogs/img/from-head-img.jpg";
        }
      }
    }
    arr.push(img);
    arr.push(name);
  }
  return arr;
}

//右边的信息
function rightMsg(s) {
  // alert(data);
  const msgBox = $.qu(".aui-chat");
  const dv = document.createElement('div');
  dv.className = 'aui-chat-item aui-chat-right';
  dv.innerHTML = `<div class="aui-chat-media">
                    <img src="${userInfos.headimgurl}">
                </div>
                <div class="aui-chat-inner">
                    
                    <div class="aui-chat-content">
                        <div class="aui-chat-arrow"></div>
                        ${s}
                    </div>
                    <div class="aui-chat-status">
                        <i class="aui-iconfont aui-icon-info aui-text-danger"></i>
                    </div>
                </div>`;
  msgBox.appendChild(dv);
  msgBox.scrollTop = msgBox.scrollHeight;
}

function toObject(obj) {
  let rs = obj;
  rs = typeof rs == "object" ? rs : JSON.parse(rs);
  return rs;
}
function getAllUsers(cb) {
  //var url = 'http://127.0.0.1:3031/user/api/getUserList?sid=1&tab=1';
  //这里获取用户信息做了缓存
  ajax.get(`${cfg.ogs.host}${cfg.ogs.allUsers}`, `sid=${11}&tab=${1}`, (rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      if (r.rc == 200) {
        // sessionStorage.setItem("allUsers", infos);
        // console.log("所有信息:",r.userinfo);
        cb(r.userinfo);
      } else {
        alert("获取信息失败");
      }
    } else {
      alert("获取信息失败");
    }
  });
}



